import React from 'react';

import { ReactComponent as Trashcan } from '@/assets/images/profile/Delete.svg';
import { getUserId } from '@/entities/auth/model/selectors';
import { editProfile } from '@/entities/profile/model/actions';
import { getAvatarList, getEditProfileLoading, getUserAvatar } from '@/entities/profile/model/selectors';
import { Dropzone } from '@/features/Dropzone';
import { env } from '@/shared/constants';
import { ModalContext } from '@/shared/context/ModalContext';
import { getImageUrl, storage } from '@/shared/lib';
import { useMetaTag } from '@/shared/lib/hooks';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, Modal } from '@/shared/ui';
import axios from 'axios';
import Image from 'next/image';
import { useRouter } from 'next/router';

import cs from './EditAvatar.module.scss';

export const EditAvatar = () => {
  const userAvatar = useAppSelector(getUserAvatar);
  const [activeItem, setActiveItem] = React.useState<number | null>();
  const avatarList = useAppSelector(getAvatarList);
  const isLoading = useAppSelector(getEditProfileLoading);
  const [found, setFound] = React.useState<boolean>(false);
  const dispatch = useAppDispatch();
  const userId = useAppSelector(getUserId);
  const router = useRouter();
  const { closeModal, data } = React.useContext(ModalContext);
  useMetaTag(true, '#999999');
  const handleSubmit = (file: string, index?: number) => {
    if (index === activeItem && found) {
      return;
    }
    index && setActiveItem(index);
    dispatch(editProfile({ id: userId as number, profile: { ...data, avatar: file } })).then(() => {
      closeModal();
      router.reload();
    });
  };

  const addFileToServer = async (files: File[] = []) => {
    // функция нужна для того,
    // чтобы отправлять файл на сервер.
    // Там генерится ссылка на файл,
    // мы же получаем название файла.
    // Это название патчим в аватар пользователя,
    // либо куда нужно
    const accessToken = storage.getAccessToken();
    const formData = new FormData();
    formData.append('file', files[0]);

    const response = await axios.post(`${env.apiUrl}/files`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data.file;
  };

  const handleChange = (files: File[] = []) => {
    addFileToServer(files).then((res) => {
      dispatch(editProfile({ id: userId as number, profile: { ...data, avatar: String(res) } })).then(() => {
        closeModal();
        router.reload();
      });
    });
  };

  React.useEffect(() => {
    const item = avatarList.find((item) => item.file === userAvatar)?.id;
    if (item) {
      setActiveItem(item as number);
      setFound(true);
    }
  }, [userAvatar]);
  return (
    <Modal className={cs.modal} isOpen onCloseClick={closeModal}>
      <h2 className={cs.title}>Аватар</h2>
      <div className={cs.choose}>
        {avatarList.map((item) => (
          <span className={item.id === activeItem ? cs.active_span : cs.non_active_span} key={item.id}>
            <Image
              alt={`${item.id}`}
              className={cs.item}
              height={56}
              key={item.id}
              onClick={() => handleSubmit(item.file, item.id)}
              quality={100}
              sizes="(max-width: 768px) 48vw, (max-width: 1024px) 24vw, (max-width: 1366px) 12vw, 8vw"
              src={getImageUrl(item.file)}
              width={56}
            />
          </span>
        ))}
      </div>
      <Dropzone isLoading={isLoading} onChange={handleChange} />
      {!isLoading && avatarList.findIndex((item) => item.file === userAvatar) === -1 && (
        <Button className={cs.delete} onClick={() => handleSubmit(avatarList[0].file)} variant={ButtonVariants.Logout}>
          <Trashcan />
          Удалить фото
        </Button>
      )}
    </Modal>
  );
};
